package com.xcity.game.buff;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcity.game.buff.impl.BuffFinishBuild;

import naga.x.App;
import naga.x.game.template.TemplateService;

public class BuffFactory {

	public static Buff create(int buffId) {
		BuffTemplate temp = App.getApp().getServiceManager().get(TemplateService.class).get(BuffTemplate.class, buffId);
		if (temp.getEffectId() == BuffEffector.BUFF_FINISH_BUILD_AT_ONCE) {
			return new BuffFinishBuild(buffId, temp);
		}
		return new Buff(buffId, temp);
	}
	
	public static Buff create(String json) {
		JSONObject obj = JSON.parseObject(json);
		return create(obj);
	}
	
	public static Buff create(JSONObject jsonObj) {
		int buffId = jsonObj.getIntValue(Buff.FIELD_ID);
		long createTime = jsonObj.getLongValue(Buff.FIELD_CREATE_TIME);
		int usedTimes = jsonObj.getIntValue(Buff.FIELD_USED_TIMES);
		int duration = jsonObj.getIntValue(Buff.FIELD_DURATION);
		BuffTemplate template = App.getApp().getServiceManager().get(TemplateService.class).get(BuffTemplate.class, buffId);
		if (template.getEffectId() == BuffEffector.BUFF_FINISH_BUILD_AT_ONCE) {
			return new BuffFinishBuild(buffId, createTime, usedTimes, duration, template);
		}
		return new Buff(buffId, createTime, usedTimes, duration, template);
	}
	
	public static List<Buff> createBuffs(String jsonArr) {
		JSONArray arr = JSON.parseArray(jsonArr);
		int size;
		if (arr == null || (size = arr.size()) == 0) {
			return new ArrayList<Buff>();
		}
		List<Buff> buffs = new ArrayList<Buff>(size + 2);
		for (int i = 0; i < size; i++) {
			JSONObject obj = arr.getJSONObject(i);
			buffs.add(create(obj));
		}
		return buffs;
	}
	
}
